package com.example.demo.config;

import com.example.demo.common.base.Result;
import com.example.demo.common.base.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Bin.L
 * @date: 2022/6/29 17:36
 * @description: 全剧异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalWebExceptionHandler {


    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> validateErrorHandler(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String errorMessage = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        log.error("参数校验异常：{}", errorMessage);
        return Results.failure(errorMessage);
    }

}
